package com.hippo.core.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hippo.core.util.CaseGenerator;
import com.hippo.core.util.CommonUtil;
import com.hippo.core.util.ExportExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author: hippo
 */
@Service
@Slf4j
public class CaseGenerateService {

    public JSONObject generateCase(JSONObject obj) throws Exception {
        CaseGenerator caseGenerator = new CaseGenerator();
        // 基本信息对象
        JSONObject infoObj = obj.getJSONObject("info");
        String functionName = infoObj.getString("name");
        // 前置条件对象
        JSONObject preconditionObj = obj.getJSONObject("precondition");
        // 通用的前置条件
        String preconditionStr = caseGenerator.generatePrecondition(preconditionObj);
        // 其他条件
        String otherConditions = preconditionObj.getString("otherConditions");
        // 操作id
        String operateId = obj.getString("operateId");
        // 新建编辑表单公共数组
        JSONArray newEditForm = obj.getJSONArray("newEditForm");
        // 删除对象
        JSONObject deleteOperation = obj.getJSONObject("deleteOperation");
        // 列表检索数组
        JSONArray listSearch = obj.getJSONArray("listSearch");
        //  列表排序数组
        JSONArray listSort = obj.getJSONArray("listSort");
        // 启动停止对象
        JSONObject startStopOperation = obj.getJSONObject("startStopOperation");
        ArrayList<HashMap<String, Object>> lists = new ArrayList<>();
        try {
            switch (operateId) {
                case "1":
                case "2": // 新建编辑表单
                    lists = caseGenerator.newEditForm(infoObj, newEditForm, operateId);
                    break;
                case "3": // 删除操作
                    lists = caseGenerator.deleteOperation(infoObj, deleteOperation);
                    break;
                case "4": // 列表检索
                    lists = caseGenerator.listSearch(functionName, listSearch);
                    break;
                case "5": // 列表排序
                    lists = caseGenerator.listSort(functionName, listSort);
                    break;
                case "6": // 列表分页
                    lists = caseGenerator.listPaging(functionName);
                    break;
                case "7": // 启停操作
                    lists = caseGenerator.startStopOperation(infoObj, startStopOperation);
                    break;
            }
            String level = infoObj.getString("level");
            JSONObject jsonObject = caseGenerator.generateMinderData(functionName, lists, level, preconditionStr, otherConditions);
            return CommonUtil.successJson(jsonObject);
        } catch (Exception e) {
            log.error(e.toString());
//            e.printStackTrace();
            return CommonUtil.errorJson("生成失败，请检查配置信息");
        }
    }

    public void exportCaseExcel(JSONObject jsonObject, HttpServletResponse response) throws Exception {
        List<Object[]> list = new ArrayList<>();
        String[] rowName = {"用例名称", "所属模块", "标签", "前置条件", "备注", "步骤描述", "预期结果", "编辑模式", "用例等级", "责任人", "用例状态"};
        String functionName = jsonObject.getJSONObject("root").getJSONObject("data").getString("text");
        String userId = jsonObject.getString("id");
        String version = jsonObject.getString("version");
        String moduleName = jsonObject.getString("moduleName");
        JSONObject dict = JSONObject.parseObject("{\"1\":\"P0\",\"2\":\"P1\",\"3\":\"P2\"}");
        jsonObject.getJSONObject("root").getJSONArray("children").forEach(item -> {
            JSONObject caseObj = JSONObject.parseObject(JSON.toJSONString(item));
            String level = caseObj.getJSONObject("data").getString("priority") != null
                    ? dict.getString(caseObj.getJSONObject("data").getString("priority"))
                    : caseObj.getJSONObject("data").getJSONArray("resource").getString(1);
            String step = "";
            String result = "";
            String precondition = "";
            String caseName = caseObj.getJSONObject("data").getString("text");
            for (int i = 0; i < caseObj.getJSONArray("children").size(); i++) {
                JSONObject caseObj1 = JSONObject.parseObject(JSON.toJSONString(caseObj.getJSONArray("children").get(i)));
                if (i == 0) {
                    precondition = caseObj1.getJSONObject("data").getString("text");
                } else {
                    step += i + ". " + caseObj1.getJSONObject("data").getString("text");
                    result += i + ". " + (JSONObject.parseObject(JSON.toJSONString(caseObj1.getJSONArray("children").get(0))).
                            getJSONObject("data").getString("text")
                            .replace("1.", "①.").replace("2.", "②.").replace("3.", "③.")
                            .replace("4.", "④.").replace("5.", "⑤.").replace("6.", "⑥.")
                            .replace("\n", ""));
                    if (i != caseObj.getJSONArray("children").size() - 1) {
                        step += "\n";
                        result += "\n";
                    }
                }
            }
            Object[] data = {caseName, moduleName + "/" + functionName, version, precondition, "", step, result, "STEP", level, userId, "Prepare"};
            list.add(data);
        });
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        String fileName = "用例生成" + moduleName.replace("/", "-") + "-" + functionName;
        response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xlsx");
        response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "FileName");
        response.setContentType("application/octet-stream;charset=utf-8");
        OutputStream outPutStream = response.getOutputStream();
        ExportExcel exportExcel = new ExportExcel("用例生成", rowName, list);
        exportExcel.export(outPutStream);
        outPutStream.flush();
        outPutStream.close();
    }
}
